@echo off
setlocal enabledelayedexpansion
set preport=0

:restart
set empty=Empty

for /f "tokens=1 delims=[]" %%a in ('hdc list targets') do (
    if "%%a" == "%empty%" (
        echo Target not found,Reconnecting
        hdc tconn %1:%2
    ) 
)
set count=0;
for /f "tokens=*" %%a in ('hdc shell "cat /proc/net/unix | grep devtools"') do (
    set /a count+=1
)

if %count% GTR 1 (
    echo Too many devtools processes
    timeout /t 1 /nobreak >nul
    goto restart
)

for /f "tokens=4 delims=_" %%a in ('hdc shell "cat /proc/net/unix | grep devtools"') do (
    if %%a NEQ %preport% (
        echo port changed   
        hdc fport rm tcp:9222 localabstract:webview_devtools_remote_%preport%
        set preport=%%a
        hdc fport tcp:9222 localabstract:webview_devtools_remote_!preport!
    )
)

timeout /t 1 /nobreak >nul
goto restart